//
//  MyService.swift
//  WaiBao
//
//  Created by 赵佟越 on 17/5/12.
//  Copyright © 2017年 zhaotongyue. All rights reserved.
//

import Foundation
import Moya
import RxSwift
import SwiftyJSON
//import ObjectMapper



// 网络请求结构体
struct MyNetwork {
    
    // 请求成功的回调
    typealias successCallback = (_ result: Any) -> Void
    // 请求失败的回调
    typealias failureCallback = (_ error: MoyaError) -> Void
    
    // 单例
    static let provider = MoyaProvider<MyService>()
    
    // 发送网络请求
    static func request(
        target: MyService,
        success: @escaping successCallback,
        failure: @escaping failureCallback
        ) {
        
        provider.request(target) { result in
            switch result {
            case let .success(moyaResponse):
                do {
                    try success(moyaResponse.mapJSON()) 
                } catch {
                    failure(MoyaError.jsonMapping(moyaResponse))
                }
            case let .failure(error):
                failure(error)
            }
        }
    }
}


enum MyService {
    case home(user_id:String)//index
    case goods_list(page: String,limit:String)

    case pay_goods(user_id: String, goods_id: String)//充能接口
    case signin(user_id: String)// 签到
    case signinfo(user_id: String)// 签到详情
    case signInList(user_id: String)// 签到列表
    
    case register(mobile: String , password:String,invite_user_mobile:String, nick_name:String)//注册
    case loginOfPwd(mobile: String,password:String)// 登陆
    case sendcode(mobile: String,token:String,type:String)// 发送验证码
    case checkcode(mobile: String,type:String,code:String)// 验证验证码
    
    case updateLoginpwd(user_id: String,new_password:String)// 修改登录密码
    case updatepwd(mobile: String,new_password:String)// 修改支付密码
    case updateUserinfo(user_id: String,nick_name:String,headImg:String,check_type:String)// 修改个人信息
    case uploadimg(imgcode: NSData)// 上传图片
    case updateUserMobile(user_id: String,new_mobile:String)// 修改手机号
    case userinfo(user_id: String)//
    case getMlist(user_id: String,page :String,limit:String)
    case getDKElist(user_id: String,page :String,limit:String)// DKE收支明细
    case getNlist(user_id: String,page :String,limit:String)//N值收支明细
    case newAccount(user_id: String,password:String)// 创建以太坊地址
    case bindAccount(user_id: String,account:String,keystore:String)// 创建以太坊地址
    
    
    case chongNengList(user_id: String,page :String,limit:String)
    case baozhiNlist(user_id: String,page :String,limit:String)
    case baoZhiM(user_id: String,trade_id :String,value:String,type:String)
    
    case checkPayPwd(user_id: String,pay_password :String)//验证支付密码
    case getTwoWay(user_id: String)
    case getTwoWayNdetail(user_id: String,type:String)
    
    case dkeOut(user_id: String,vlaue:String)//DKE转出
    case dkeInto(user_id: String,vlaue:String,password:String)//DKE转入
    case dayPriceWay(page: String,limit:String,type:String)//市场价走势
    case dkeWay(page: String,limit:String,type:String)//dke走势
    case dkeXing(user_id: String)//星球页面内容
    case miningProgress(user_id: String,limit:String,page:String,type:String)//星球页面内容
    case miningInfo(wk_id: String,limit:String,page:String)//星球页面内容

    case thirdlogin(google_id: String,mobile:String,password:String,invite_user_mobile:String)//谷歌登陆接口
    
     case checkYanzhengqi(user_id: String,code:String)//谷歌登陆接口
    case getWaydetail(user_id: String,page: String,limit:String,type:String)
    case getList(page: String,limit:String,user_id:String)
    
    case xiaoHaoLog(type:String,user_id: String,page: String,limit:String)
    case memberDKEDetail(user_id:String)
    //mobile/wk/xiaoHaoLog
    case readArticle(user_id:String,article_id:String)
    //
    case checkYanzhengqiOfName(nick_name:String,code:String)
    
    case checkAppVersion(device:String)
    case relieveBindAccount(userId:String)
}


// MARK: - TargetType Protocol Implementation
extension MyService: TargetType  {
    
    // 请求服务器的根路径
    var baseURL: URL { return URL.init(string: "http://renedescartes.io/")! }
    
    // 每个API对应的具体page路径
    var path: String {
        switch self {
        case .home(user_id: _):
            return "mobile/index/index"
        case .goods_list(page: _, limit: _):
            return "mobile/goods/goods_list"
        case .signin( _):
            return "mobile/personal/signin"
        case .signinfo( _):
            return "mobile/personal/signinfo"
        case .signInList( _):
            return "mobile/personal/signInList"
        case .pay_goods( _,  _):
            return "mobile/goods/pay_goods"
        case .register(_,_,_, _):
            return "mobile/user/registerV2"
        case .loginOfPwd(_,  _):
            return "mobile/user/loginOfPwdV2"
        case .sendcode(_,  _, _):
            return "mobile/user/sendcode"
        case .checkcode(_,  _, _):
            return "mobile/user/checkcode"
        case .updateLoginpwd(_,  _):
            return "mobile/user/updateLoginpwdV2"
        case .updatepwd(_,  _):
            return "mobile/user/updatepwd"
        case .updateUserinfo(_,  _, _,_):
            return "mobile/user/updateUserinfo"
        case .uploadimg(_):
            return "mobile/user/uploadimg"
        case .updateUserMobile(_,  _):
            return "mobile/user/updateUserMobile"
        case .userinfo(_):
            return "mobile/user/userinfo"
        case .getMlist(_,_,_):
            return "mobile/index/getMlist"
            
        case .newAccount(_,_):
            return "mobile/index/newAccount"
        case .getDKElist(_,_,_):
            return "mobile/index/getDKElist"
        case .getNlist(_,_,_):
            return "mobile/index/getNlist"

        case .chongNengList(_,_,_):
            return "mobile/index/chongNengList"
        case .baoZhiM(_,_,_,_):
            return "mobile/index/baoZhiM"
        case .checkPayPwd(_,_):
            return "mobile/user/checkPayPwd"
        case .getTwoWay(_):
            
            return "mobile/two_way/getTwoWay"
        case .getTwoWayNdetail(_,_):
            return "mobile/two_way/getTwoWayNdetail"
        case .dkeOut(_,_):
            return "mobile/index/dkeOut"
        case .dkeInto(_,_,_):
            return "mobile/index/dkeInto"
        case .dayPriceWay(_,_,_):
            return "mobile/wk/dayPriceWay"
        case .dkeWay(_,_,_):
            return "mobile/wk/dkeWay"
        case .dkeXing(_):
            return "mobile/wk/dkeXing"
        case .miningProgress(_):
            return "mobile/wk/miningProgressV2"
        case .thirdlogin(_,_,_,_):
            return "mobile/user/thirdlogin"
        case .checkYanzhengqi(_,_):
            return "mobile/user/checkYanzhengqi"
            
        case .baozhiNlist(_,_,_):
            return "mobile/index/baozhiNlist"
        case .miningInfo(_,_,_):
            return "mobile/wk/miningInfo"
        case .bindAccount(_):
            return "mobile/user/bindAccount"
        case .getWaydetail(_):
            return "mobile/two_way/getWaydetail"
        case .getList(_):
            return "mobile/article/getList"
        case .xiaoHaoLog(_):
            return "mobile/wk/xiaoHaoLog"
        case .memberDKEDetail(_):
            return "mobile/index/memberDKEDetail"
        case .readArticle(_):
            return "mobile/personal/readArticle"
        case .checkYanzhengqiOfName:
            return "mobile/user/checkYanzhengqiOfName"
        case .checkAppVersion(_):
            return "mobile/index/getVersion"
        case .relieveBindAccount(_):
            return "/mobile/user/unBindAccount"
        }
    }
    
    // 各个接口的请求方式，get或post
    var method: Moya.Method {
        switch self {
        case .goods_list, .pay_goods:
            return .post
        default:
            return .post
        }
    }
    
    
    
    // 请求是否携带参数，如果需要参数，就做如demo2和demo3的设置
    var task: Task {
        let appkey = "83847437837439234394834"
        let dat = NSDate.init(timeIntervalSinceNow: 0)
        let a = dat.timeIntervalSince1970
        let timeString =  String(format: "%0.f", a)

        let appKeyStr = String(format:"%@%@",appkey,timeString)
        
        
        switch self {
        case let .home(user_id):
            let dic:[String:String]  = ["user_id" : user_id,"sign":appKeyStr,"time":timeString];
            return .requestParameters(parameters: dic, encoding: URLEncoding.default)
        
        case let .goods_list(page, limits):
            return .requestParameters(parameters: ["page" : page,"limits":limits,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case let .pay_goods(user_id, goods_id): // 带有参数,注意前面的let
            return .requestParameters(parameters: ["user_id" : user_id, "goods_id" : goods_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .signin(let user_id):
            return .requestParameters(parameters: ["user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .signinfo(let user_id):
            return .requestParameters(parameters: ["user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .signInList(let user_id):
            return .requestParameters(parameters: ["user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .register(let mobile, let password,let invite_user_mobile, let nick_name):
            
            return .requestParameters(parameters: ["invite_code":invite_user_mobile,"nick_name" : mobile,"password":password,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .loginOfPwd(let mobile, let password):
            return .requestParameters(parameters: ["password" : password,"nick_name" : mobile,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .sendcode(let mobile, let token, let type):
            return .requestParameters(parameters: ["token" : token,"type" : type,"mobile" : mobile,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .checkcode(let mobile, let type, let code):
            return .requestParameters(parameters: ["code" : code,"type" : type,"mobile" : mobile,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .updateLoginpwd(let user_id, let new_password):
            return .requestParameters(parameters: ["new_password" : new_password,"nick_name" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .updatepwd(let mobile, let new_password):
            return .requestParameters(parameters: ["new_password" : new_password,"user_id" : mobile,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .updateUserinfo(let user_id, let nick_name, let headImg, let check_type):
            var mDic = NSMutableDictionary()
            mDic = ["mobile" : user_id,"sign":appKeyStr,"time":timeString]
            if nick_name == ""{
//                mDic["nick_name"] = nil
            }else{
                mDic["nick_name"] = nick_name
            }
            if headImg == ""{
//                mDic["headImg"] = nil
            }else{
                mDic["headImg"] = headImg
            }
            
            if check_type == ""{
                //                mDic["headImg"] = nil
            }else{
                mDic["check_type"] = check_type
            }
            

            
            return .requestParameters(parameters: mDic as! [String : Any] , encoding: URLEncoding.default)
        case .uploadimg(let imgcode):
            return .requestParameters(parameters: ["imgcode" : imgcode,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .updateUserMobile(let user_id, let new_mobile):
            return .requestParameters(parameters: ["new_mobile" : new_mobile,"user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .userinfo(let user_id):
            return .requestParameters(parameters: ["user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .getMlist(let user_id, let page, let limit):
            return .requestParameters(parameters: ["user_id" : user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .newAccount(let user_id, let password):
            return .requestParameters(parameters: ["user_id" : user_id,"password":password,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
            
        case .getDKElist(let user_id, let page, let limit):
            return .requestParameters(parameters: ["user_id" : user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .getNlist(let user_id, let page, let limit):
            return .requestParameters(parameters: ["user_id" : user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        
        case .baoZhiM(let user_id, let trade_id, let value, let type):
            return .requestParameters(parameters: ["type":type,"user_id" : user_id,"wk_id":trade_id,"value":value,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
            
        case .chongNengList(let user_id, let page, let limit):
            return .requestParameters(parameters: ["user_id" : user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .checkPayPwd(let user_id, let pay_password):
            return .requestParameters(parameters: ["user_id" : user_id,"pay_password":pay_password,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .getTwoWay(let user_id):
            return .requestParameters(parameters: ["user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .getTwoWayNdetail(let user_id, let type):
            return .requestParameters(parameters: ["user_id" : user_id,"type":type,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .dkeOut(let user_id, let vlaue):
            return .requestParameters(parameters: ["user_id" : user_id,"value":vlaue,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .dkeInto(let user_id, let vlaue, let password):
            return .requestParameters(parameters: ["user_id" : user_id,"value":vlaue,"password":password,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .dayPriceWay(let page, let limit,let type):
            return .requestParameters(parameters: ["type":type,"page" : page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .dkeWay(let page, let limit,let type):
            return .requestParameters(parameters: ["type":type,"page" : page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .dkeXing(let user_id):
            return .requestParameters(parameters: ["user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .miningProgress(let user_id, let limit, let page, let type):
            return .requestParameters(parameters: ["limit" : limit,"page" : page,"type" : type,"user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .thirdlogin(let google_id, let mobile, let password, let invite_user_mobile):
            return .requestParameters(parameters:
            ["invite_user_mobile":invite_user_mobile,"google_id":google_id,"mobile" : mobile,"password":password,"sign":appKeyStr,"time":timeString],encoding:URLEncoding.default)
        case .checkYanzhengqi(let user_id, let code):
            return .requestParameters(parameters:
                ["user_id" : user_id,"code":code,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
            
        case .baozhiNlist(let user_id, let page, let limit):
            return .requestParameters(parameters: ["limit":limit,"user_id" : user_id,"page":page,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .miningInfo(let wk_id, let limit, let page):
            return .requestParameters(parameters: ["limit":limit,"wk_id" : wk_id,"page":page,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .bindAccount(let user_id, let account, let keystore):
            return .requestParameters(parameters:
                ["keystore":keystore,"account":account,"user_id" : user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .getWaydetail(let user_id, let page, let limit,let type):
            return .requestParameters(parameters: ["user_id" : user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString,"type":type], encoding: URLEncoding.default)
        case .getList(let page, let limit, let user_id):
            return .requestParameters(parameters: ["user_id":user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .xiaoHaoLog(let type, let user_id, let page, let limit):
            return .requestParameters(parameters: ["type":type,"user_id":user_id,"page":page,"limit":limit,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .memberDKEDetail(let user_id):
            return .requestParameters(parameters: ["user_id":user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .readArticle(let user_id, let article_id):
            return .requestParameters(parameters: ["article_id":article_id,"user_id":user_id,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .checkYanzhengqiOfName(let nick_name, let code):
            return .requestParameters(parameters: ["code":code,"nick_name":nick_name,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
//        case .checkAppVersion(let device):
//            return .requestParameters(parameters: ["device":device], encoding: URLEncoding.default)
//        }
        case .checkAppVersion(let device):
            return .requestParameters(parameters: ["device":device,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
        case .relieveBindAccount(let userid):
            return .requestParameters(parameters: ["user_id":userid,"sign":appKeyStr,"time":timeString], encoding: URLEncoding.default)
            
        }
    }
    
    // 单元测试使用
    var sampleData: Data {
        switch self {
        case .home, .goods_list:
            return "just for test".utf8Encoded
        default:
            return "just for test".utf8Encoded
        }
    }
    
    // 请求头
    var headers: [String : String]? {
        return ["Content-type" : "application/x-www-form-urlencoded"]
    }
}

// 扩展方法
private extension String {
    var urlEscaped: String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    var utf8Encoded: Data {
        return data(using: .utf8)!
    }
}

enum RxSwiftMoyaError: String {
    case ParseJSONError
    case OtherError
}

extension RxSwiftMoyaError: Swift.Error { }

